package com.bw.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.common.domain.Shop;
import com.bw.common.domain.ShopVo;
import com.bw.common.result.PageResult;
import com.bw.common.result.Result;
import com.bw.common.utils.StringUtils;
import com.bw.es.service.EsService;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author：HaoYunde
 * @Package：com.bw.es.service.impl
 * @Project：hyd-boot
 * @name：EsServiceImpl
 * @Date：2024/6/17 11:00
 */
@Service
@Log4j2
public class EsServiceImpl implements EsService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;



    @Override
    public Result addEs(List<Shop> list) {
        try {
            BulkRequest bulkRequest = new BulkRequest();
            for (Shop shop : list) {
                bulkRequest.add(new IndexRequest("shop")
                        .id(shop.getShopId()+"")
                        .source(JSONObject.toJSONString(shop), XContentType.JSON));
            }
            restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.info("报错了:{}",e);
        }
        return Result.success();
    }


    @Override
    public Result<PageResult<Shop>> findShopList(ShopVo shopVo) {
        long total=0;
        ArrayList<Shop> shops = new ArrayList<>();
        try {
            SearchRequest request = new SearchRequest("shop");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            if(StringUtils.isNotBlank(shopVo.getShopName())){
                boolQueryBuilder.must(QueryBuilders.matchQuery("shopName",shopVo.getShopName()));
            }
            searchSourceBuilder.query(boolQueryBuilder);
            searchSourceBuilder.from((shopVo.getPageNum()-1)*shopVo.getPageSize());
            searchSourceBuilder.size(shopVo.getPageSize());
            searchSourceBuilder.sort("shopTime", SortOrder.DESC);
            searchSourceBuilder.highlighter(new HighlightBuilder()
                    .field("shopName")
                    .preTags("<span style=\"color:red\">")
                    .postTags("</span>"));
            request.source(searchSourceBuilder);
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHits hits = search.getHits();
            total= hits.getTotalHits().value;
            SearchHit[] hits1 = hits.getHits();
            for (SearchHit documentFields : hits1) {
                String sourceAsString = documentFields.getSourceAsString();
                Shop shop = JSONObject.parseObject(sourceAsString, Shop.class);
                Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
                if(highlightFields!=null){
                    HighlightField highlightField = highlightFields.get("shopName");
                    if(highlightField!=null){
                        Text[] fragments = highlightField.getFragments();
                        String str="";
                        for (Text fragment : fragments) {
                            str+=fragment;
                            shop.setShopName(str);
                        }
                    }
                }
                shops.add(shop);
            }
        } catch (Exception e) {
            log.info("报错了:{}",e);
        }
        return PageResult.toResult(total,shops);
    }


}
